package com.minimalist.common.feign.encoder;

import jakarta.activation.MimetypesFileTypeMap;

import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author 11987
 */
public class ByteArrayMultipartFile implements MultipartFile{
    private final String name;
    private final String originalFilename;
    private final String contentType;
    private final byte[] bytes;

    @Override
    public boolean isEmpty(){
        return this.bytes.length == 0;
    }

    @Override
    public long getSize(){
        return this.bytes.length;
    }

    @NotNull
    @Override
    public InputStream getInputStream(){
        return new ByteArrayInputStream(this.bytes);
    }


    @Override
    public void transferTo(@NotNull File destination) throws IOException{
        try (FileOutputStream outputStream = new FileOutputStream(destination)){
            outputStream.write(this.bytes);
        }
    }

    public String getName() {
        return name;
    }

    public String getOriginalFilename() {
        return originalFilename;
    }

    public String getContentType() {
        return contentType;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public ByteArrayMultipartFile(String name, String originalFilename, String contentType, byte[] bytes){
        if (bytes == null){
            throw new NullPointerException("bytes is marked @NonNull but is null");
        } else{
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.bytes = bytes;
        }
    }

    public ByteArrayMultipartFile(File file){
        this.name = file.getName();
        this.originalFilename = file.getName();
        this.contentType = new MimetypesFileTypeMap().getContentType(file);
        try (FileInputStream fis = new FileInputStream(file)){
            this.bytes = IOUtils.toByteArray(fis);
        } catch (Exception e){
            throw new IllegalArgumentException("文件内容读取失败!");
        }
    }
}

